import { Paths } from "@/Paths";
import { Bottom } from "@/component/Bottom";
import Button from "@/component/Button";
import { Dropdown } from "@/component/Dropdown";
import { Input } from "@/component/Input";
import useToast from "@/component/Toast";
import { Text } from "@/gimd";
import devices from 'current-device';
import { useCallback, useEffect, useRef, useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router";
import Show from "../../component/Show";
import { ApiHttp } from "../../network/ApiHttp";
import { GlobalStore } from "../../store/GlobalStore";
import { LoginModal } from "./LoginModal";
import { MemberRow } from "./MemberRow";
import { Space } from "./Space";
import styles from "./index.module.scss";
import { log_error } from "./log_error";
import { SVG } from "@/gimd/SVG";
import { Edit } from "@/art";

function r_str(a = ''): string {
  const len = a.length;
  let b = '';
  for (let i = 0; i < len; i += 2) {
    if (i === len - 1) {
      const c = a.charCodeAt(i);
      b += String.fromCharCode((255 - c) % 255);
    } else {
      const d = a.charCodeAt(i + 1);
      const c = a.charCodeAt(i);
      b += String.fromCharCode((255 - d) % 255);
      b += String.fromCharCode((255 - c) % 255);
    }
  }
  return b;
}

const words = [
  r_str('\x8F\x90\x91\x9A\x8Cß\x8C\x9A\x92\x9E\x9A'),
  r_str('\x9A\x8D\x96\x98\x8B\x8C\x8D\x9A'),
];
export default function Main() {
  const nav = useNavigate();
  const hello = useRef('');
  const [{
    sesame, session_id,
    site_name, site_breif, is_me, username,
  }, dispatch] = GlobalStore.useStore();

  const [submitting, setSubmitting] = useState(false)
  const [loading, setLoading] = useState(false)
  const [siteName, setSiteName] = useState(site_name)
  const [siteBreif, setSiteBreif] = useState(site_breif)
  const [editingSiteBreif, setEditingSiteBreif] = useState(false)
  const [editingSiteName, setEditingName] = useState(false)

  const reload = useCallback((c?: AbortController) => {
    setLoading(true)
    ApiHttp.get('blog/main_site', void 0, { ...c })
      .then(r => r.data)
      .then(r => {
        setSiteName(r.blog_name);
        setSiteBreif(r.blog_breif);
        setEditingSiteBreif(false);
        setEditingName(false);
        dispatch({ type: 'site_info', payload: { site_name: r.blog_name, site_breif: r.blog_breif, is_me: r.is_me } });
      })
      .catch(ApiHttp.ignoreAbort)
      .catch(log_error)
      .finally(() => setLoading(false));
  }, [dispatch])

  useEffect(() => {
    const c = new AbortController()
    reload(c);
    dispatch({ type: 'sesame', payload: false })
    return () => c.abort()
  }, [dispatch, reload, session_id])

  const check_word = useCallback((key: string, mode: 0 | 1) => {
    if (mode) hello.current = key;
    else hello.current += key;

    const hit_word = words.findIndex(word => word === hello.current)
    if (hit_word >= 0) {
      switch (hit_word) {
        case 0:
          dispatch({ type: 'sesame', payload: true })
          break;
        case 1:
          dispatch({ type: 'sesame2', payload: true })
          break;
      }
      hello.current = ''
    } else if (words.findIndex(word => word.startsWith(hello.current)) < 0) {
      hello.current = ''
    }
  }, [dispatch])

  useEffect(() => {
    if (sesame) return;
    const onKeyDown = (e: KeyboardEvent) => e.key && check_word(e.key.toLowerCase(), 0);
    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [check_word, sesame])

  const [toast, toast_ctx] = useToast();
  const editMainSite = () => {
    if (submitting) return;
    if (siteBreif === site_breif && siteName === site_name) return;
    setSubmitting(true)
    ApiHttp.post(`blog/main_site`, void 0, {
      blog_breif: siteBreif,
      blog_name: siteName
    }).then(() => {
      toast("修改成功")
      reload()
    }).catch(ApiHttp.ignoreAbort)
      .catch(log_error)
      .finally(() => setSubmitting(false))
  }
  const { pathname } = useLocation()
  useEffect(() => {
    const route_title = Paths.Titles[pathname as Paths.All];
    if (route_title) document.title = site_name + ': ' + route_title
    return () => {
      document.title = site_name
    };
  }, [pathname, site_name])

  const [show_sesame_input, set_show_sesame_input] = useState(false);

  const ref_timer_id = useRef<ReturnType<typeof setTimeout> | null>(null)
  const on_touch_start = useCallback(() => {
    ref_timer_id.current = setTimeout(() => {
      set_show_sesame_input(!show_sesame_input)
      ref_timer_id.current = null
    }, 5000)
  }, [show_sesame_input])

  const on_touch_end = useCallback(() => {
    if (ref_timer_id.current) clearTimeout(ref_timer_id.current);
    ref_timer_id.current = null
  }, [])

  return (
    <div className={styles.main_page}>
      {toast_ctx}
      <div className={styles.main_top_bar}>
        <div className={styles.main_top_bar_fist_row}>
          <h1 className={styles.main_title}>
            <Show yes={!editingSiteName}>
              <Button size='s' onClick={() => nav('/')}>
                <Text tag='h1' className={styles.main_title}>
                  {siteName}
                </Text>
              </Button>
            </Show>
            <Show yes={editingSiteName}>
              <input
                type="text"
                value={siteName}
                onBlur={e => {
                  setSiteName(e.target.value.trim())
                  setEditingName(false)
                  editMainSite()
                }}
                onChange={e => setSiteName(e.target.value)}
                autoFocus
                maxLength={32} />
            </Show>
          </h1>
          <Show yes={is_me && !editingSiteName}>
            <Button size='s' onClick={() => setEditingName(true)} kind="icon">
              <SVG c={Edit} width={12} height={12} />
            </Button>
          </Show>
          <Space className={styles.end_zone}>
            <Button
              size='s'
              href={Paths.All.Main}
              title='首页'
              no_jump
              onClick={() => nav(Paths.All.Main)}>
              首页
            </Button>
            <Dropdown
              forceRender
              anchorX={1}
              alignX={1}
              size='m'
              triggers={[devices.desktop() ? 'hover' : 'click']}
              menu={{
                items: [
                  {
                    children: <>splittings.dom.js</>,
                    open: 'https://splittings.gim.ink',
                    title: 'splittings.dom.js'
                  },
                  {
                    disabled: window.is_sad_day,
                    children: <>Firework</>,
                    no_jump: true,
                    href: Paths.All.Firework,
                    title: '烟花',
                    onClick: () => nav(Paths.All.Firework)
                  },
                  {
                    disabled: window.is_sad_day,
                    children: <>LF2:Wemake</>,
                    open: 'https://lf2.gim.ink',
                    title: 'LF2:Wemake'
                  },
                  {
                    children: <>Writeboard</>,
                    open: 'https://writeboard.gim.ink',
                    title: 'Writeboard'
                  },
                  {
                    disabled: window.is_sad_day,
                    children: <>ChineseChess</>,
                    no_jump: true,
                    title: '中国象棋',
                    href: Paths.All.ChineseChess,
                    onClick: () => nav(Paths.All.ChineseChess)
                  },
                  {
                    disabled: window.is_sad_day,
                    children: <>Chess</>,
                    no_jump: true,
                    title: '国际象棋',
                    href: Paths.All.Chess,
                    onClick: () => nav(Paths.All.Chess)
                  },
                  {
                    children: <>bebavior_net_test</>,
                    open: 'https://lf2.gim.ink/bebavior_net_test',
                    title: 'go to https://lf2.gim.ink/bebavior_net_test'
                  },
                  {
                    children: <>quad_tree_test</>,
                    open: 'https://lf2.gim.ink/quad_tree_test',
                    title: 'go to https://lf2.gim.ink/quad_tree_test'
                  },
                  {
                    disabled: window.is_sad_day,
                    children: <>Bounce</>,
                    no_jump: true,
                    title: '弹跳传说',
                    href: Paths.All.Bounce,
                    onClick: () => nav(Paths.All.Bounce)
                  },
                ]
              }} >
              <Button size='s'> 更多 </Button>
            </Dropdown>
            <Button
              size='s'
              href={Paths.All.About}
              title='关于'
              no_jump
              onTouchStart={on_touch_start}
              onTouchEnd={on_touch_end}
              onTouchCancel={on_touch_end}
              onClick={() => nav(Paths.All.About)}>
              关于
            </Button>
            <Show yes={!!session_id}>
              <MemberRow />
            </Show>
          </Space>
        </div>
        <Show.Div yes={show_sesame_input}>
          <Input placeholder="sesame?" onChange={e => check_word(e.target.value.toLowerCase(), 1)} />
        </Show.Div>

        <div className={styles.main_subtitle}>
          <Show yes={!editingSiteBreif}>
            <span>{siteBreif}</span>
            <Show yes={is_me}>
              <Button size='s' onClick={() => setEditingSiteBreif(true)} kind="icon">
                <SVG c={Edit} width={12} height={12} />
              </Button>
            </Show>
          </Show>
          <Show yes={editingSiteBreif}>
            <input
              type="text"
              value={siteBreif}
              onBlur={e => {
                setSiteBreif(e.target.value.trim())
                setEditingSiteBreif(false)
                editMainSite()
              }}
              onChange={e => setSiteBreif(e.target.value)}
              autoFocus
              maxLength={128} />
          </Show>
        </div>
      </div>
      <Outlet />
      <Bottom />
      <LoginModal />
    </div>
  );
}
